<?php

namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Queue;
use think\Request;
use think\Validate;

class Api extends Controller
{
	/**
	 * 短信发送
	 * */
	public function sendSms()
	{
		$input = Request()->param();

		$mobile = $input['mobile'];

		$is_use = Db::name('user')->where(['mobile' => $mobile])->count();
		if ($is_use) apiReturn(2, '该手机号已经被使用');

		//获取手机号
		$pattern = "/^(13[0-9]|14[5|7]|15[0-9]|18[0-9]|19[4|5])\d{8}$/";
		if (empty($mobile)) {
			apiReturn(2, '请输入手机号');
		} else {
			if (preg_match($pattern, $mobile)) {
				//判断当前手机有没有发送过验证码
				$result = Db::name('sms_code')->where(array('mobile' => $mobile))->order('create_time desc')->find();
				$result = time() - $result['create_time'];
				if ($result < 60 and $result > 0) return apiReturn(2, '当前手机号操作频繁,请60秒后发送');

				$authnum = rand(100000, 999999);
				$statusStr = array(
					"0" => 1,
					"-1" => "参数不全",
					"-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
					"30" => "密码错误",
					"40" => "账号不存在",
					"41" => "余额不足",
					"42" => "帐户已过期",
					"43" => "IP地址限制",
					"50" => "内容含有敏感词"
				);
				$smsapi = "http://api.smsbao.com/";
				$user = C('WEB_SMS_ACC'); //短信平台帐号
				$pass = md5(C('WEB_SMS_PWD')); //短信平台密码
				$content = "【水珠】验证码" . $authnum . "如非本人操作，请忽略。";//要发送的短信内容
				$phone = $mobile;//要发送短信的手机号码
				$sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $phone . "&c=" . urlencode($content);
				$result = file_get_contents($sendurl);
				if ($result == 0) {
					$info['code'] = $authnum;
					$info['mobile'] = $phone;
					$info['create_time'] = time();
					$info['failure_time'] = time() + 600;//失效时间：10分钟
					Db::name('sms_code')->insert($info);

					apiReturn(1, '短信发送成功');
				} else {
					apiReturn(2, $statusStr[$result]);
				}
			} else {
				apiReturn(2, '手机号格式错误');
			}
		}
	}

	public function userRegister()
	{
		$input = Request()->param();

		$mobile = $input['mobile'];
		$password = $input['password'];
		$re_password = $input['re_password'];
		$code = $input['code'];

		if (empty($mobile)) apiReturn(2, '请输入手机号');
		$mobile_pattern = "/^(13[0-9]|14[5|7]|15[0-9]|18[0-9]|19[4|5])\d{8}$/";
		if (!preg_match($mobile_pattern, $mobile)) apiReturn(2, '手机号格式错误');

		$count = Db::name('user')->where(['mobile' => $mobile])->count();
		if ($count > 0) apiReturn(2, '该手机号已被使用');

		if (empty($password)) apiReturn(2, '请输入密码');
		if (empty($password)) apiReturn(2, '请输入确认密码');
		if (strlen($password) < 6) apiReturn(2, '密码长度至少为6位');
		if ($password !== $re_password) apiReturn(2, '两次密码不一致，请重新输入');
		if (empty($code)) apiReturn(2, '请输入验证码');

		$sms_info = Db::name('sms_code')->where(array('mobile' => $mobile))->order('create_time desc')->find();

		if (empty($sms_info)) apiReturn(2, '该手机号未发送验证码');
		if ($code != $sms_info['code']) apiReturn(2, '验证码错误');
		if ($sms_info['status'] == 1) apiReturn(2, '该验证码已被使用');
		if (time() > $sms_info['failure_time']) apiReturn(2, '验证码已失效');

		$time = time();
		$expire_time = $time + C('EXPIRE_TIME') * 3600 * 24;
		$data = [
			'mobile' => $mobile,
			'password' => thinkEncrypt($password),
			'expire_time' => $expire_time,
			'create_time' => $time
		];

		Db::startTrans();
		try {
			$user_id = Db::name('user')->insertGetId($data);

			Db::name('sms_code')->where(['id' => $sms_info['id']])->setField('status', 1);

			$job_name = 'app\index\job\JobUser';
			$queue_name = "JobUser";
			$job_data = [
				'id' => $user_id,
				'type' => 'check_expire'
			];
			$task = Queue::later($expire_time - $time, $job_name, $job_data, $queue_name);
			if (!($task !== false)) {
				Db::rollback();
				apiReturn(2, '任务新增失败');
			}

			$user_info = [
				'id' => $user_id,
				'is_expire' => 0,
				'expire_time' => $expire_time
			];

			Db::commit();
			apiReturn(1, '注册成功', $user_info);
		} catch (\Exception $e) {
			Db::rollback();
			apiReturn(2, '系统繁忙，请稍后再试');
		}
	}

	public function userLogin()
	{
		$input = Request()->param();

		$mobile = $input['mobile'];
		$password = $input['password'];

		if (empty($mobile)) apiReturn(2, '请输入手机号');
		if (empty($password)) apiReturn(2, '请输入密码');

		$info = Db::name('user')->field('id,is_expire,expire_time')->where(['mobile' => $mobile])->find();
		if ($info) {
			if ($info['is_expire'] == 0) {
				apiReturn(1, '登录成功', $info);
			} else {
				apiReturn(2, '账号已过期');
			}
		} else {
			apiReturn(2, '账号不存在');
		}
	}

	/**
	 * 版本检测
	 * */
	public function checkVersion()
	{
		$input = Request()->param();

		$version = $input['version'];

		if (empty($version)) apiReturn(2, '请输入版本号');

		if ($version < C('VERSION')) {
			apiReturn(3, '检测到新版本', C('VERSION_URL'));
		} else {
			apiReturn(1, '当前为最新版本');
		}
	}

	/**
	 * 获取openid
	 * */
	public function getOpenid()
	{
		$input = Request()->param();

		$code = $input['code'];

		if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

		$appid = C('XCX_APPID');
		$secret = C('XCX_SECRET');
		$grant_type = 'authorization_code';
		$url = 'https://api.weixin.qq.com/sns/jscode2session?';

		$param = [
			'appid' => $appid,
			'secret' => $secret,
			'js_code' => $code,
			'grant_type' => $grant_type
		];
		$param_str = http_build_query($param);
		$url .= $param_str;

		$user_data = json_decode(file_get_contents($url));

		apiReturn(1, '获取数据成功', $user_data);
	}

	/**
	 * 微信登录
	 * */
	public function wxLogin()
	{
		$input = Request()->param();

		$code = $input['code'];
		$encryptedData = $input['encryptedData'];
		$iv = $input['iv'];

		if (empty($encryptedData)) apiReturn(2, 'encryptedData不能为空');
		if (empty($iv)) apiReturn(2, 'iv不能为空');

		$appid = C('XCX_APPID');
		$secret = C('XCX_SECRET');
		$grant_type = 'authorization_code';
		$url = 'https://api.weixin.qq.com/sns/jscode2session?';
		$param = [
			'appid' => $appid,
			'secret' => $secret,
			'js_code' => $code,
			'grant_type' => $grant_type
		];
		$param_str = http_build_query($param);
		$url .= $param_str;
		$user_data = json_decode(file_get_contents($url));

		$session_key = $user_data->session_key;

		$data = "";
		Loader::import('wxLogin\wxBizDataCrypt', EXTEND_PATH);
		$obj = new \WXBizDataCrypt($appid, $session_key);
		$errCode = $obj->decryptData($encryptedData, $iv, $data);

		if ($errCode == 0) {
			$data = json_decode($data, true);

			$username = $data['nickName'];
			$avatar = $data['avatarUrl'];
			$openid = $user_data->openid;

			$save_data = [
				'username' => $username,
				'avatar' => $avatar,
				'openid' => $openid
			];
			$data = bindUser($save_data);

			if ($data) {
				apiReturn(1, '登录成功', $data);
			} else {
				apiReturn(2, '登录失败');
			}
		} else {
			file_put_contents(RUNTIME_PATH . 'login_error.log', 'code：' . $code . '；encryptedData：' . $encryptedData . '；iv：' . $iv . '；errCode' . $errCode . PHP_EOL);

			apiReturn(2, '登录失败，错误码：' . $errCode);
		}
	}

	/**
	 * 获取手机号
	 * */
	public function getMobile()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$code = $input['code'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
		if (empty($code) || $code == 'undefined') apiReturn(2, 'code缺失');

		$token = get_access_token('xcx_access_token.json', 2);
		if (empty($token)) apiReturn(2, 'TOKEN缺失');

		$url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token . '&code=' . $code;

		$data = [
			'code' => $code
		];
		$result = httpsRequest($url, json_encode($data));
		$result = json_decode($result, true);

		if ($result['errcode'] == 0) {
			$mobile = $result['phone_info']['phoneNumber'];

			if ($mobile) {
				$count = Db::name('user')->where(['mobile' => $mobile])->count();
				if ($count > 0) apiReturn(2, '手机号码已存在');

				$update_user_data['mobile'] = $mobile;

				$user_info = Db::name('user')->field('level,up_user_id')->where(['id' => $user_id])->find();
				if ($user_info['level'] == 1 && $user_info['up_user_id'] > 0) {
					$update_user_data['level'] = 2;

					// 某个用户的级别变更需要将其所有上级都加入到用户升级的任务计划
					addAllUpUserToUpPlan($user_id);
				}

				Db::name('user')->where(['id' => $user_id])->update($update_user_data);

				apiReturn(1, '获取数据成功', $mobile);
			} else {
				file_put_contents(RUNTIME_PATH . 'mobileErrGetMobile.txt', '手机号不存在===>' . json_encode($result, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
				apiReturn(2, '系统繁忙，请稍后再试');
			}
		} else {
			file_put_contents(RUNTIME_PATH . 'ApiErrGetMobile.txt', '时间：' . date('Y-m-d H:i:s') . '，用户ID：' . $user_id . ' ===> 错误码：' . $result['errcode'] . '；错误信息：' . $result['errmsg'] . '；code：' . $code . PHP_EOL, FILE_APPEND);
			if ($result['errcode'] == 40001) {
				apiReturn(2, '系统繁忙，请重新获取手机号');
			} else if ($result['errcode'] == 40029) {
				apiReturn(3, '获取手机号失败，请前往【我 => 设置 => 关于微信】将微信版本更新至不低于8.0.16后，再回到此界面点击绑定手机');
			} else {
				apiReturn(2, '系统繁忙，请稍后再试~');
			}
		}
	}

	/**
	 * 首页banner
	 * */
	public function indexBanner()
	{
		$banner_list = Db::name('banner')->field('id,img,type,to_id')->select();

		if ($banner_list) {
			foreach ($banner_list as &$v) {
				$v['img'] = getPicture($v['img']);
			}
			apiReturn(1, '获取数据成功', $banner_list);
		} else {
			apiReturn(2, '暂无更多数据', []);
		}
	}

	/**
	 * banner文章详情
	 * */
	public function bannerArticleDetail()
	{
		$input = Request()->param();

		$id = $input['id'];

		if (empty($id)) apiReturn(2, '文章ID缺失');

		$info = Db::name('article')->field('id,title,content,create_time')->where(['id' => $id])->find();
		if ($info) {
			$info['content'] = doEditorContent($info['content']);
			$info['create_time'] = timeFormat($info['create_time']);

			apiReturn(1, '获取数据成功', $info);
		} else {
			apiReturn(2, '文章不存在或已删除');
		}
	}

	/**
	 * 商品分类
	 * */
	public function goodsTypeList()
	{
		$list = Db::name('goods_type')->field('id,name')->where(['pid' => 0])->order('sort asc')->select();

		if ($list) {
			apiReturn(1, '获取数据成功', $list);
		} else {
			apiReturn(2, '暂无更多数据', []);
		}
	}

	/**
	 * 商品品牌
	 * */
	public function goodsBrandList()
	{
		$list = Db::name('goods_brand')->field('id,name')->order('sort asc')->select();

		if ($list) {
			apiReturn(1, '获取数据成', $list);
		} else {
			apiReturn(2, '暂无更多数据', []);
		}
	}

	/**
	 * 商品列表
	 * */
	public function goodsList()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$name = $input['name'];
		$one_type_id = $input['one_type_id'] ?: 0;
		$brand_id = $input['brand_id'] ?: 0;
		$sort = $input['sort'] ?: 0;//0：综合，1：销量，2：价格升序，3：价格升序
		$page = $input['page'] ?: 1;
		$pagesize = $input['pagesize'] ?: 10;

		$where['upper'] = 1;

		if ($name) $where['name'] = ['LIKE', '%' . $name . '%'];
		if ($one_type_id) $where['one_type_id'] = $one_type_id;
		if ($brand_id) $where['brand_id'] = $brand_id;

		switch ($sort) {
			case 1:
				$order = 'sales_count desc';
				break;
			case 2:
				$order = 'min_price asc';
				break;
			case 3:
				$order = 'min_price desc';
				break;
			default:
				$order = 'id desc';
				break;
		}

		$goods_list = Db::name('goods')->field('id,img,name,min_price,sales_count')->where($where)->order($order)->page($page, $pagesize)->select();
		if ($goods_list) {
			foreach ($goods_list as &$v) {
				$v['img'] = getPicture($v['img']);
			}
			apiReturn(1, '获取数据成功', $goods_list);
		} else {
			apiReturn(2, '暂无更多数据', []);
		}
	}

	/**
	 * 商品详情
	 * */
	public function goodsDetail()
	{
		$input = Request()->param();

		$id = $input['id'];
		$user_id = $input['user_id'];

		if (empty($id)) apiReturn(2, '商品ID缺失');

		$info = Db::name('goods')->field('id,name,img,imgs,sales_count,min_price,content,user_instructions,product_param')->where(['id' => $id])->find();
		if ($info) {
			$info['img'] = getPicture($info['img']);
			$info['imgs'] = doImgs($info['imgs']);
			$min_market_price = Db::name('sku_value')->where(['goods_id' => $id, 'status' => 1])->min('market_price');
			$info['min_market_price'] = sprintf('%.2f', $min_market_price);
			$info['content'] = doEditorContent($info['content']);
			$info['product_param'] = json_decode($info['product_param'], true);

			if ($user_id) {
				$collect_count = Db::name('collect')->where(['to_id' => $id, 'user_id' => $user_id, 'status' => 1])->count();
				$info['collect_status'] = $collect_count ? true : false;
			} else {
				$info['collect_status'] = false;
			}

			$sku_data = getSku($id);

			$info['sku_list'] = $sku_data['sku_list'];
			$info['sku_value_list'] = $sku_data['sku_value_list'];

			$comment_count = Db::name('goods_comment')->where(['goods_id' => $id])->count();
			$info['comment_count'] = $comment_count;

			//评价列表
			$comment_list = Db::name('goods_comment c')
				->join('tp_user u', 'c.user_id = u.id', 'left')
				->field('c.id,u.avatar,u.username,c.star,c.content,c.imgs,c.create_time')
				->where(['c.goods_id' => $id])
				->order('c.create_time desc')
				->limit(2)
				->select();
			if ($comment_list) {
				foreach ($comment_list as &$v) {
					$v['avatar'] = doAvatar($v['avatar']);
					$v['imgs'] = doImgs($v['imgs']);
					$v['star'] = intval($v['star']);
					$v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
				}
			} else {
				$comment_list = [];
			}
			$info['comment_list'] = $comment_list;

			// 服务保障
			$service_guarantee = Db::name('goods_service_guarantee')->value('service_guarantee');
			$service_guarantee_arr = json_decode($service_guarantee, true);
			$info['service_guarantee'] = $service_guarantee_arr;
			$info['service_guarantee_show'] = implode('·', array_column($service_guarantee_arr, 'param'));

			apiReturn(1, '获取数据成功', $info);
		} else {
			apiReturn(2, '商品不存在或已删除');
		}
	}

	/**
	 * 收藏/取消收藏
	 * */
	public function doCollect()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$to_id = $input['to_id'];
		$type = $input['type'];    //1：商品
		$status = $input['status'];//0：取消收藏，1：收藏

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
		if (empty($to_id)) apiReturn(2, '收藏对象ID缺失');

		$time = time();

		$info = Db::name('collect')->where(array('user_id' => $user_id, 'to_id' => $to_id, 'type' => $type))->find();
		if ($info) {
			if ($info['status'] == $status) {
				apiReturn(2, '系统繁忙，请稍后再试~');
			} else {
				$data = array(
					'status' => $status,
					'update_time' => $time,
					'create_time' => $time
				);
				$res = Db::name('collect')->where(array('id' => $info['id']))->update($data);
				$msg = $status == 0 ? '取消收藏' : '收藏';
				if ($res) {
					apiReturn(1, $msg . '成功');
				} else {
					apiReturn(2, $msg . '失败');
				}
			}
		} else {
			if ($status == 0) {
				apiReturn(2, '系统繁忙，请稍后再试~');
			} else {
				$data = array(
					'user_id' => $user_id,
					'to_id' => $to_id,
					'type' => $type,
					'status' => $status,
					'create_time' => $time
				);
				$res = Db::name('collect')->insert($data);
				if ($res) {
					apiReturn(1, '收藏成功');
				} else {
					apiReturn(2, '收藏失败');
				}
			}
		}
	}

	/**
	 * 商品评价列表
	 * */
	public function goodsCommentList()
	{
		$input = Request()->param();

		$id = $input['id'];
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($id)) apiReturn(2, '商品ID缺失');

		$list = Db::name('goods_comment c')
			->join('tp_user u', 'c.user_id = u.id', 'left')
			->field('c.id,u.avatar,u.username,c.star,c.content,c.imgs,c.create_time')
			->where(['c.goods_id' => $id])
			->order('c.create_time desc')
			->page($page, $pagesize)
			->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['avatar'] = doAvatar($v['avatar']);
				$v['imgs'] = doImgs($v['imgs']);
				$v['star'] = intval($v['star']);
				$v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
			}

			apiReturn(1, '获取数据成功', $list);
		} else {
			apiReturn(2, '暂无更多数据', []);
		}
	}

	/**
	 * 购物车商品数量校正
	 * tips：在小程序 onHide 和 onUnload 中调用该接口
	 * */
	public function doCarGoodsCount()
	{
		$input = Request()->param();;
		$car_list = json_decode($input['car_list'], true);//[{"id":"4","count":"8"}]
		if ($car_list) {
			foreach ($car_list as &$v) {
				Db::name('goods_car')->where(array('id' => $v['id']))->setField('count', $v['count']);
			}
		}
	}

	/**
	 * 加入购物车
	 * */
	public function addGoodsCar()
	{
		$input = Request()->param();;

		$id = $input['id'];//商品id
		$user_id = $input['user_id'];
		$sku_id = $input['sku_id'];//属性id组合；sku_value表sku_id
		$count = $input['count'];

		if (empty($id)) apiReturn(2, '商品ID缺失');
		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
		if (empty($sku_id)) apiReturn(2, '属性ID缺失');
		if ($count <= 0) apiReturn(2, '商品数量异常');

		$goods_info = Db::name('goods')->where(['id' => $id])->find();
		if ($goods_info) {
			$sku_info = Db::name('sku_value')->field('sku_id,img,price,stock')->where(['sku_id' => $sku_id, 'goods_id' => $id])->find();
			if ($sku_info) {
				if ($sku_info['stock'] < $count) apiReturn(2, '商品所选属性库存不足');

				$car_info = Db::name('goods_car')->where(['user_id' => $user_id, 'goods_id' => $id, 'sku_id' => $sku_id])->find();
				if ($car_info) {
					//该商品之前已经加入过购物车，这个时候只需要增加购物车数量即可
					$res = Db::name('goods_car')->where(['id' => $car_info['id']])->setInc('count', $count);
				} else {
					//该商品第一次加入购物车，添加购物车数据
					$data = [
						'user_id' => $user_id,
						'goods_id' => $id,
						'img' => $sku_info['img'],
						'sku_id' => $sku_info['sku_id'],
						'count' => $count,
						'price' => $sku_info['price'],
						'create_time' => time()
					];
					$res = Db::name('goods_car')->insert($data);
				}
			} else {
				apiReturn(2, '属性不存在或已删除');
			}

			if ($res) {
				apiReturn(1, '添加成功');
			} else {
				apiReturn(2, '添加购物车失败');
			}
		} else {
			apiReturn(2, '商品不存在或已删除');
		}
	}

	/**
	 * 购物车列表
	 * */
	public function goodsCarList()
	{
		$input = Request()->param();;

		$user_id = $input['user_id'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		$list = Db::name('goods_car')->where(array('user_id' => $user_id))->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['img'] = getPicture($v['img']);
				$goods_info = Db::name('goods')->where(['id' => $v['goods_id']])->find();
				$v['goods_name'] = $goods_info['name'];
				$v['actived'] = false;

				if ($sku_list = getSkuName(explode('-', $v['sku_id']))) $v['sku'] = implode('，', array_column($sku_list, 'name'));
			}

			apiReturn(1, '获取数据成功', $list);
		} else {
			apiReturn(2, '暂无数据');
		}
	}

	/**
	 * 移除购物车商品
	 * */
	public function removeGoodsCar()
	{
		$input = Request()->param();;
		$car_ids = $input['car_ids'];
		if (empty($car_ids)) apiReturn(2, '购物车ID缺失');
		$res = Db::name('goods_car')->where(array('id' => array('IN', $car_ids)))->delete();
		if ($res) {
			apiReturn(1, '移除成功');
		} else {
			apiReturn(2, '移除失败');
		}
	}

	/**
	 * 购物车订单确认页
	 * */
	public function goodsCarOrderConfirm()
	{
		$input = Request()->param();
		$user_id = $input['user_id'];
		$car_ids = $input['car_ids'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
		if (empty($car_ids)) apiReturn(2, '购物车ID缺失');

		$car_list = Db::name('goods_car')->field('id,goods_id,img,sku_id,price,count')->where(array('id' => array('IN', $car_ids)))->select();
		$all_price = 0;
		if ($car_list) {
			foreach ($car_list as &$v) {
				$v['goods_name'] = Db::name('goods')->where(['id' => $v['goods_id']])->value('name');
				$v['img'] = getPicture($v['img']);
				$v['sku'] = implode('，', array_column(getSkuName(explode('-', $v['sku_id'])), 'name'));
				$all_price += sprintf("%.2f", $v['price'] * $v['count']);
			}
			//默认收货地址
			$address_info = Db::name('address')->field('id,username,mobile,province_id,city_id,area_id,address')->where(array('user_id' => $user_id, 'is_default' => 1))->find();
			if ($address_info) {
				$address_info['province'] = getProvinceName($address_info['province_id']);
				$address_info['city'] = getCityName($address_info['city_id']);
				$address_info['area'] = getAreaName($address_info['area_id']);
				unset($address_info['province_id']);
				unset($address_info['city_id']);
				unset($address_info['area_id']);
			}

			$data = array(
				'goods_list' => $car_list,
				'all_price' => sprintf('%.2f', $all_price),
				'address' => $address_info ? $address_info : []
			);
			apiReturn(1, '获取数据成功', $data);
		} else {
			apiReturn(2, '购物车商品数据异常');
		}
	}

	/**
	 * 购物车立即支付【生成待支付订单】 之后 发起支付
	 * */
	public function addGoodsCarOrder()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$car_ids = $input['car_ids'];
		$address_id = $input['address_id'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
		if (empty($car_ids)) apiReturn(2, '购物车ID缺失');
		if (empty($address_id)) apiReturn(2, '请选择收货地址');

		$user_info = Db::name('user')->where(['id' => $user_id])->find();
		if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');

		$time = time();

		Db::startTrans();
		try {
			$car_list = Db::name('goods_car')->field('id,goods_id,price,sku_id,count')->where(array('id' => array('IN', $car_ids)))->select();
			$all_price = 0;
			$order_res = false;
			$up_order_res = true;
			$goods_order = [];
			$order_ids = '';

			if ($car_list) {
				$address_info = Db::name('address')->where(array('id' => $address_id))->find();
				//支付订单号
				$pay_order_sn = 'PAY' . date('Ymd') . rand(1000, 9999) . $user_id;

				foreach ($car_list as $k => &$v) {
					$goods_info = Db::name('goods')->field('id,name')->where(array('id' => $v['goods_id']))->find();

					$sku_info = Db::name('sku_value')->where(array('goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']))->find();
					if ($sku_info) {
						if ($v['count'] > $sku_info['stock']) apiReturn(2, $goods_info['name'] . '库存不足');
					} else {
						apiReturn(2, $goods_info['name'] . '属性不存在或已删除');
					}

					$all_price += sprintf("%.2f", $v['price'] * $v['count']);

					$now_goods_price = $v['price'] * $v['count'];

					$wait_order_info = Db::name('order')->where(array('pay_order_sn' => $pay_order_sn))->find();

					if ($wait_order_info) {
						$up_order_data = array(
							'all_price' => $now_goods_price + $wait_order_info['all_price'],
							'pay_price' => $now_goods_price + $wait_order_info['pay_price']
						);
						$up_order_res = Db::name('order')->where(array('id' => $wait_order_info['id']))->update($up_order_data);

						if (!$up_order_res) break;

						$order_res = $wait_order_info['id'];
					} else {
						//订单主表添加数据
						$order_sn = 'SN' . date('Ymd') . rand(1000, 9999) . $user_id;
						$order_data = array(
							'user_id' => $user_id,
							'order_sn' => $order_sn,
							'pay_order_sn' => $pay_order_sn,
							'all_price' => $now_goods_price,
							'pay_price' => $now_goods_price,
							'get_username' => $address_info['username'],
							'get_mobile' => $address_info['mobile'],
							'get_province' => getProvinceName($address_info['province_id']),
							'get_city' => getCityName($address_info['city_id']),
							'get_area' => getAreaName($address_info['area_id']),
							'get_address' => $address_info['address'],
							'car_ids' => $car_ids,
							'create_time' => $time
						);
						$order_res = Db::name('order')->insertGetId($order_data);
					}

					if ($order_res) {
						//当$order_res为数值时（订单ID），走该分支
						if ($order_ids == '') {
							$order_ids = $order_res;
						} else {
							$order_ids .= ',' . $order_res;
						}
					}

					if (!$order_res) break;

					//准备订单副表数据
					$goods_info = Db::name('goods')->field('id,name')->where(['id' => $v['goods_id']])->find();
					$sku_info = Db::name('sku_value')->where(['goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']])->find();
					$goods_order[] = [
						'order_id' => $order_res,
						'goods_id' => $v['goods_id'],
						'img' => $sku_info['img'],
						'name' => $goods_info['name'],
						'sku_id' => $sku_info['sku_id'],
						'price' => $sku_info['price'],
						'count' => $v['count'],
						'create_time' => $time
					];
				}
				$vice_order_res = Db::name('vice_order')->insertAll($goods_order);

				if ($order_res && $vice_order_res && $up_order_res) {
					//微信支付
					Loader::import('wxsdk\wxPay', EXTEND_PATH);
					$obj = new \wxPay();
					//调用示例（最后两个参数为可选参数）
					$pay_data = $obj->jsApi($user_info['openid'], '0.01', $pay_order_sn, '商品支付', 'https://www.baidu.com/index/index/notice', '', 1);

					$return_data = array(
						'pay_data' => $pay_data,
						'order_id' => $order_ids
					);

					Db::commit();
					apiReturn(1, '获取数据成功', $return_data);
				} else {
					Db::rollback();
					apiReturn(2, '订单生成失败');
				}
			} else {
				Db::rollback();
				apiReturn(2, '购物车商品数据异常');
			}
		} catch (\Exception $e) {
			apiReturn(2, '系统繁忙，请稍后再试' . $e);
		}
	}

	/**
	 * 商品确认订单
	 * */
	public function confirmOrder()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$goods_id = $input['goods_id'];
		$sku_id = $input['sku_id'];
		$count = $input['count'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
		if (empty($goods_id)) apiReturn(2, '商品ID缺失');
		if (empty($sku_id)) apiReturn(2, '属性ID缺失');
		if (empty($count)) apiReturn(2, '商品数量异常');

		$sku_list = Db::name('sku_value')->field('sku_id,img,price,goods_id')->where(array('sku_id' => $sku_id, 'goods_id' => $goods_id))->select();
		if ($sku_list) {
			foreach ($sku_list as &$v) {
				$v['goods_name'] = Db::name('goods')->where(['id' => $v['goods_id']])->value('name');
				$v['img'] = getPicture($v['img']);
				$v['sku'] = implode('，', array_column(getSkuName(explode('-', $v['sku_id'])), 'name'));
				$all_price = sprintf("%.2f", $v['price'] * $count);
			}

			//默认收货地址
			$default_address = Db::name('address')->field('id,username,mobile,province_id,city_id,area_id,address')->where(['user_id' => $user_id])->order('is_default desc,id desc')->find();
			if ($default_address) {
				$default_address['address'] = getProvinceName($default_address['province_id']) . getCityName($default_address['city_id']) . getAreaName($default_address['area_id']) . $default_address['address'];
				unset($default_address['province_id']);
				unset($default_address['city_id']);
				unset($default_address['area_id']);
			}

			$data = array(
				'goods_list' => $sku_list,
				'all_price' => $all_price,
				'address' => $default_address ? $default_address : []
			);

			apiReturn(1, '获取数据成功', $data);
		} else {
			apiReturn(2, '规格不存在或已删除');
		}
	}

	/**
	 * 立即支付【生成待支付订单】 之后 发起支付
	 * */
	public function addGoodsOrder()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$goods_id = $input['goods_id'];
		$count = $input['count'];
		$sku_id = $input['sku_id'];
		$address_id = $input['address_id'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
		if (empty($goods_id)) apiReturn(2, '商品ID缺失');
		if ($count <= 0) apiReturn(2, '商品数量异常');
		if (empty($sku_id)) apiReturn(2, '属性ID缺失');
		if (empty($address_id)) apiReturn(2, '请选择收货地址');

		$user_info = Db::name('user')->where(['id' => $user_id])->find();
		if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');

		$time = time();

		$goods_info = Db::name('goods')->field('id,name')->where(array('id' => $goods_id))->find();
		if ($goods_info) {
			$sku_info = Db::name('sku_value')->where(array('sku_id' => $sku_id))->find();
			if ($sku_info) {
				//商品库存
				if ($count > $sku_info['stock']) apiReturn(2, '商品库存不足');

				$address_info = Db::name('address')->where(array('id' => $address_id))->find();

				$all_price = $sku_info['price'] * $count;

				$order_sn = 'SN' . date('Ymd') . rand(1000, 9999) . $user_id;
				$data = array(
					'user_id' => $user_id,
					'order_sn' => $order_sn,
					'pay_order_sn' => $order_sn,
					'all_price' => $all_price,
					'pay_price' => $all_price,
					'get_username' => $address_info['username'],
					'get_mobile' => $address_info['mobile'],
					'get_province' => getProvinceName($address_info['province_id']),
					'get_city' => getCityName($address_info['city_id']),
					'get_area' => getAreaName($address_info['area_id']),
					'get_address' => $address_info['address'],
					'create_time' => $time
				);

				$res = Db::name('order')->insertGetId($data);
				if ($res) {
					$goods_order = array(
						'order_id' => $res,
						'goods_id' => $goods_id,
						'img' => $sku_info['img'],
						'name' => $goods_info['name'],
						'sku_id' => $sku_id,
						'price' => $sku_info['price'],
						'count' => $count,
						'create_time' => $time
					);
					Db::name('vice_order')->insert($goods_order);

					Loader::import('wxsdk\wxPay', EXTEND_PATH);
					$obj = new \wxPay();
					//调用示例（最后两个参数为可选参数）
					$pay_data = $obj->jsApi($user_info['openid'], '0.01', $order_sn, '商品支付', 'https://www.baidu.com/index/index/notice', '', 1);

					$return_data = array(
						'pay_data' => $pay_data,
						'order_id' => $res
					);

					apiReturn(1, '获取数据成功', $return_data);
				} else {
					apiReturn(2, '生成订单失败');
				}
			} else {
				apiReturn(2, '规格不存在或已删除');
			}
		} else {
			apiReturn(2, '商品不存在或已删除');
		}
	}

	/**
	 * 收货地址列表
	 * */
	public function addressList()
	{
		$input = Request()->param();
		$user_id = $input['user_id'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		$list = Db::name('address')->field('id,username,mobile,province_id,city_id,area_id,address,is_default')->where(['user_id' => $user_id])->order('is_default desc,create_time desc')->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['province'] = getProvinceName($v['province_id']);
				$v['city'] = getCityName($v['city_id']);
				$v['area'] = getAreaName($v['area_id']);
			}
			apiReturn(1, '获取数据成功', $list);
		} else {
			apiReturn(2, '暂无收货地址', []);
		}
	}

	/**
	 * 收货地址详情
	 * */
	public function addressDetail()
	{
		$input = Request()->param();

		$id = $input['id'];

		if (empty($id)) apiReturn(2, '收货地址ID缺失');

		$info = Db::name('address')->field('id,username,mobile,province_id,city_id,area_id,address,is_default')->where(array('id' => $id))->find();
		if ($info) {
			$info['region'] = array(getProvinceName($info['province_id']), getCityName($info['city_id']), getAreaName($info['area_id']));
			$info['defaultIndex'] = $info['is_default'] == 1 ? 0 : 1;

			apiReturn(1, '获取数据成功', $info);
		} else {
			apiReturn(2, '收货地址不存在或已删除');
		}
	}

	/**
	 * 添加收货地址
	 * */
	public function addAddress()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$username = $input['username'];
		$mobile = $input['mobile'];
		$province = $input['province'];
		$city = $input['city'];
		$area = $input['area'];
		$address = $input['address'];
		$is_default = $input['is_default'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
		if (empty($province) || empty($city) || empty($area) || empty($address)) apiReturn(2, '请完善收货地址');
		if (empty($username)) apiReturn(2, '请填写收货人姓名');
		if (empty($mobile)) apiReturn(2, '请填写联系方式');

		if ($is_default == 1) {
			//查询默认的收货地址
			$default_info = Db::name('address')->where(array('user_id' => $user_id, 'is_default' => 1))->find();
		} else {
			//查询是不是第一个收货地址，是第一个收货地址的话，就设置成默认的
			$count = Db::name('address')->where(array('user_id' => $user_id))->count();
			if ($count == 0) $is_default = 1;
		}
		$data = [
			'user_id' => $user_id,
			'username' => $username,
			'mobile' => $mobile,
			'province_id' => getProvinceId($province),
			'city_id' => getCityId($province, $city),
			'area_id' => getAreaId($province, $city, $area),
			'address' => $address,
			'is_default' => $is_default,
			'create_time' => time()
		];
		$res = Db::name('address')->insert($data);
		if ($res) {
			Db::name('address')->where(array('id' => $default_info['id']))->setField('is_default', 0);
			apiReturn(1, '添加成功');
		} else {
			apiReturn(2, '添加失败');
		}
	}

	/**
	 * 编辑收货地址
	 * */
	public function editAddress()
	{
		$input = Request()->param();

		$id = $input['id'];
		$username = $input['username'];
		$mobile = $input['mobile'];
		$province = $input['province'];
		$city = $input['city'];
		$area = $input['area'];
		$address = $input['address'];
		$is_default = $input['is_default'];

		if (empty($id)) apiReturn(2, '收货地址ID缺失');
		if (empty($province) || empty($city) || empty($area) || empty($address)) apiReturn(2, '请完善收货地址');
		if (empty($username)) apiReturn(2, '请填写收货人姓名');
		if (empty($mobile)) apiReturn(2, '请填写联系方式');

		//查询默认的收货地址
		$default_info = Db::name('address')->where(['id' => $id])->find();
		$data = [
			'username' => $username,
			'mobile' => $mobile,
			'province_id' => getProvinceId($province),
			'city_id' => getCityId($province, $city),
			'area_id' => getAreaId($province, $city, $area),
			'address' => $address,
			'is_default' => $is_default,
			'update_time' => time()
		];
		$res = Db::name('address')->where(['id' => $id])->update($data);
		if ($res) {
			if ($is_default == 1) {
				if ($default_info['is_default'] != 1) {
					//将原来的默认收货地址修改成非默认
					Db::name('address')->where(['user_id' => $default_info['user_id'], 'is_default' => 1, 'id' => ['neq', $id]])->setField('is_default', 0);
				}
			}
			apiReturn(1, '编辑成功');
		} else {
			apiReturn(2, '编辑失败');
		}
	}

	/**
	 * 删除收货地址
	 * */
	public function delAddress()
	{
		$input = Request()->param();

		$id = $input['id'];

		if (empty($id)) apiReturn(2, '收货地址ID缺失');

		$info = Db::name('address')->where(['id' => $id])->find();
		if ($info) {
			$res = Db::name('address')->where(['id' => $id])->delete();
			if ($res) {
				apiReturn(1, '删除成功');
			} else {
				apiReturn(2, '删除失败');
			}
		} else {
			apiReturn(2, '收货地址不存在或已删除');
		}
	}

	/**
	 * 最新消息
	 * */
	public function newMsgList()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$page = $input['page'] ?: 1;
		$pagesize = $input['pagesize'] ?: 10;

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		// 分页起始位置
		$offset = ($page - 1) * $pagesize;
		// 未读信息条件
		$where = '(user_id = ' . $user_id . ' or user_id = 0)';
		// 未读
		$sql = 'select id,order_id,title,content,read_user,type,create_time from ' . config('database.prefix') . 'msg where ' . $where . ' order by find_in_set(read_user, ' . $user_id . '),create_time desc limit ' . $offset . ', ' . $pagesize;
		$list = Db::name('msg')->query($sql);
		if ($list) {
			foreach ($list as &$v) {
				$v['is_read'] = in_array($user_id, explode(',', $v['read_user'])) ? true : false;
				$v['content'] = doEditorContent($v['content']);
				$v['create_time'] = timeFormat($v['create_time'], 'Y.m.d H:i');
			}
			apiReturn(1, '获取数据成功', $list);
		} else {
			apiReturn(2, '暂无更多数据', []);
		}
	}

	/**
	 * 分类消息列表
	 * */
	public function msgList()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$type = $input['type'] ?: 1;
		$page = $input['page'] ?: 1;
		$pagesize = $input['pagesize'] ?: 10;

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		// 分页起始位置
		$offset = ($page - 1) * $pagesize;
		// 未读信息条件
		$where = '(user_id = ' . $user_id . ' or user_id = 0) and type = ' . $type;
		// 未读
		$sql = 'select id,order_id,title,content,read_user,type,create_time from ' . config('database.prefix') . 'msg where ' . $where . ' order by find_in_set(read_user, ' . $user_id . '),create_time desc limit ' . $offset . ', ' . $pagesize;
		$list = Db::name('msg')->query($sql);
		if ($list) {
			foreach ($list as &$v) {
				$v['is_read'] = in_array($user_id, explode(',', $v['read_user'])) ? true : false;
				$v['content'] = doEditorContent($v['content']);
				$v['create_time'] = timeFormat($v['create_time'], 'Y.m.d H:i');
			}
			apiReturn(1, '获取数据成功', $list);
		} else {
			apiReturn(2, '暂无更多数据', []);
		}
	}

	/**
	 * 消息详情
	 * */
	public function msgDetail()
	{
		$input = Request()->param();

		$id = $input['id'];
		$user_id = $input['user_id'];

		if (empty($id)) apiReturn(2, '消息ID缺失');
		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		$info = Db::name('msg')->field('id,title,content,read_user,create_time')->where(['id' => $id])->find();
		if ($info) {
			$info['content'] = doEditorContent($info['content']);
			$info['create_time'] = timeFormat($info['create_time'], 'Y.m.d H:i');

			Db::name('msg')->where(['id' => $id])->setInc('look_count');

			$is_read = in_array($user_id, explode(',', $info['read_user'])) ? true : false;
			if (!$is_read) Db::name('msg')->where(['id' => $id])->setField('read_user', $info['read_user'] ? $info['read_user'] . ',' . $user_id : $user_id);

			apiReturn(1, '获取数据成功', $info);
		} else {
			apiReturn(2, '消息不存在或已删除');
		}
	}

	/**
	 * 个人中心
	 * */
	public function userCenter()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		$info = Db::name('user')->field('id,avatar,username')->where(['id' => $user_id])->find();
		if ($info) {
			$info['avatar'] = doAvatar($info['avatar']);

			$order_where = [
				'user_id' => $user_id,
				'is_pay' => 1,
				'is_del' => 0,
				'back_order_sn' => ''
			];
			// 待发货订单数量
			$wait_send_order_count = Db::name('order')->where($order_where)->where(['status' => 2])->count();
			// 待收货订单数量
			$wait_get_order_count = Db::name('order')->where($order_where)->where(['status' => 3])->count();
			// 待评价订单数量
			$wait_comment_order_count = Db::name('order')->where($order_where)->where(['status' => 4])->count();
			// 售后中订单数量
			$after_order_count = Db::name('order')->where($order_where)->where(['status' => 7])->count();
			// 待付款订单数量
			$order_where['is_pay'] = 0;
			$wait_pay_order_count = Db::name('order')->where($order_where)->where(['status' => 1])->count();

			$info['wait_pay_order_count'] = $wait_pay_order_count;
			$info['wait_send_order_count'] = $wait_send_order_count;
			$info['wait_get_order_count'] = $wait_get_order_count;
			$info['wait_comment_order_count'] = $wait_comment_order_count;
			$info['after_order_count'] = $after_order_count;

			apiReturn(1, '获取数据成功', $info);
		} else {
			apiReturn(2, '用户不存在或已禁用');
		}
	}

	/**
	 * 我的收益详情
	 * */
	public function userProfit()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		// 自己消费总额
		$me_all_consume = $this->getMeConsume($user_id);

		// 总累计销售额 = 我和我的所有下线的消费统计
		$all_consume = $me_all_consume + action('Algorithm/Algorithm/allConsume', ['user_id' => $user_id]);
		/**
		 * 个人零售销售额 = 自己消费总额中除去自己首次消费金额
		 * */
		// 自己首次消费金额
		$first_consume = Db::name('order')->where(['user_id' => $user_id, 'is_pay' => 1, 'complete_time' => ['neq', 0]])->order('id asc')->value('pay_price');
		// 个人零售销售额 = 自己消费总额 - 自己首次消费金额
		$me_consume = sprintf('%.2f', $me_all_consume - $first_consume);

		$profit_where = [
			'user_id' => $user_id,
			'status' => ['neq', -1],
			'type' => ['IN', [1, 2, 3]]
		];
		// 总累计收益
		$all_profit = Db::name('profit')->where($profit_where)->sum('price');
		// 可用收益
		$normal_profit = Db::name('user')->where(['id' => $user_id])->value('all_profit');
		// 冻结收益
		$frozen_profit = Db::name('profit')->where($profit_where)->where(['status' => 1])->sum('price');

		$info = [
			'all_consume' => sprintf('%.2f', $all_consume),
			'me_consume' => sprintf('%.2f', $me_consume),
			'all_profit' => sprintf('%.2f', $all_profit),
			'normal_profit' => sprintf('%.2f', $normal_profit),
			'frozen_profit' => sprintf('%.2f', $frozen_profit),
		];

		apiReturn(1, '获取数据成功', $info);
	}

	/**
	 * 收益明细
	 * */
	public function profitList()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$page = $input['page'] ?: 1;
		$pagesize = $input['pagesize'] ?: 10;

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		$profit_where = [
			'user_id' => $user_id,
			'status' => ['neq', -1]
		];
		$profit_list = Db::name('profit')->field('id,order_id,user_id,type,price,remark,create_time')->where($profit_where)->order('create_time desc')->page($page, $pagesize)->select();
		if ($profit_list) {
			foreach ($profit_list as &$v) {
				if ($v['type'] == 1 || $v['type'] == 2 || $v['type'] == 3) {
					$pay_user_id = Db::name('order')->where(['id' => $v['order_id']])->value('user_id');
					if ($pay_user_id) {
						$user_info = Db::name('user')->field('username,gender')->where(['id' => $pay_user_id])->find();
						$username = cutSubstr($user_info['username']);
						if (mb_strlen($username) > 6) $username = cutSubstr($username, 6);
					}
				} else {
					$username = '';
				}

				switch ($v['type']) {
					case 2:
					case 1:
						$desc = ' 成功购买了商品';
						$change = 'plus';
						break;
					case 3:
						$desc = '消费，您获得服务津贴';
						$change = 'plus';
						break;
					case 4:
						$desc = '购物收益抵扣';
						$change = 'minus';
						break;
					case 5:
						$desc = '收益提现';
						$change = 'minus';
						break;
					case 6:
					case 7:
					case 9:
						$desc = $v['remark'];
						$change = 'plus';
						break;
					case 8:
						$desc = '收益提现审核失败，收益返还';
						$change = 'plus';
						break;
					case 10:
						$desc = '充值收益';
						$change = 'plus';
						break;
					case 11:
						$desc = '处罚收益';
						$change = 'minus';
						break;
					case 12:
						$desc = '购物抵扣收益退款';
						$change = 'plus';
						break;
				}

				$v['username'] = $username;
				$v['desc'] = $desc;
				$v['change'] = $change;

				$v['create_time'] = timeFormat($v['create_time']);
			}
			apiReturn(1, '获取数据成功', $profit_list);
		} else {
			apiReturn(2, '暂无更多数据', []);
		}
	}

	/**
	 * 提现记录
	 * */
	public function withdrawalList()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$page = $input['page'] ?: 1;
		$pagesize = $input['pagesize'] ?: 10;

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		$list = Db::name('withdrawal')->field('id,real_price price,type,status,create_time')->where(['user_id' => $user_id])->order('create_time desc')->page($page, $pagesize)->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['desc'] = $v['status'] == 1 ? '提现到' . ($v['type'] == 1 ? '微信钱包' : '银行卡') : '提现审核失败';
				$v['change'] = $v['status'] == 1 ? 'plus' : 'minus';
				$v['create_time'] = timeFormat($v['create_time']);
			}
			apiReturn(1, '获取数据成功', $list);
		} else {
			apiReturn(2, '暂无更多数据', []);
		}
	}

	/**
	 * 提现页面数据回显
	 * */
	public function withdrawalInfo()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		$user_info = Db::name('user')->field('id,all_profit,real_name,bank_name,bank_num,bank_deposit')->where(['id' => $user_id])->find();

		$empty_bank = ['请选择'];
		$bank_list = C('BANK_LIST');
		$bank_list = array_merge($empty_bank, $bank_list);
		$bankIndex = 0;
		if ($bank_list) {
			foreach ($bank_list as $k => &$v) {
				if ($user_info['bank_name'] == $v) {
					$bankIndex = $k;
					break;
				}
			}
		}

		$withdrawal_price = C('WITHDRAWAL_PRICE');

		$service_rate = C('SERVICE_RATE');

		$data = [
			'user_info' => $user_info,
			'bank_list' => $bank_list,
			'bankIndex' => $bankIndex,
			'withdrawal_price' => $withdrawal_price,
			'service_rate' => $service_rate
		];

		apiReturn(1, '获取数据成功', $data);
	}

	/**
	 * 申请提现
	 * */
	public function applyWithdrawal()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$price = $input['price'];
		$service_rate = $input['service_rate'];
		$real_price = $input['real_price'];
		$real_name = $input['real_name'];
		$bank_name = $input['bank_name'];
		$bank_num = $input['bank_num'];
		$bank_deposit = $input['bank_deposit'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
		if (empty($price)) apiReturn(2, '请输入提现金额');
		if (empty($real_price)) apiReturn(2, '实际到账金额错误');

		$time = time();

		$withdrawal_price = C('WITHDRAWAL_PRICE');

		$start_time = strtotime(date('Y-m-d'));
		$end_time = strtotime(date('Y-m-d')) + 24 * 3600 - 1;
		$count = Db::name('withdrawal')->where(['user_id' => $user_id, 'status' => ['neq', 2], 'create_time' => ['between', [$start_time, $end_time]]])->count();
		if ($count) apiReturn(2, '每号每天限提一次');

		Db::startTrans();
		try {
			$user_info = Db::name('user')->where(['id' => $user_id])->find();

			$order_sn = uniqid();                //订单号

			if ($price <= $withdrawal_price) {
				if (empty($user_info['openid'])) apiReturn(2, 'openid缺失');

				// 提现到微信零钱
				$mchid = C('MCH_ID');          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
				$appid = C('XCX_APPID');       //微信支付申请对应的公众号的APPID
				$appKey = C('XCX_SECRET');     //微信支付申请对应的公众号的APP Key
				$apiKey = C('MCH_KEY');        //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥

				Loader::import('weixinPay\weixinPay-master\transfers', EXTEND_PATH);
				$obj = new \WxpayService($mchid, $appid, $appKey, $apiKey);

				$obj->createJsBizPackage($user_info['openid'], $price, $order_sn, $real_name);

				$data = [
					'order_sn' => $order_sn,
					'user_id' => $user_id,
					'price' => $price,
					'type' => 1,
					'create_time' => $time
				];
				Db::name('withdrawal')->insert($data);
			} else {
				if (empty($real_name) || $real_name == 'undefined') apiReturn(2, '姓名信息异常，请重新输入');
				if (empty($bank_name) || $bank_name == 'undefined' || $bank_name == '请选择') apiReturn(2, '请选择银行');
				if (empty($bank_num) || $bank_num == 'undefined') apiReturn(2, '银行卡号信息异常，请重新输入');
				if (empty($bank_deposit) || $bank_deposit == 'undefined') apiReturn(2, '开户行信息异常，请重新输入');

				// 申请提现到银行卡
				$data = [
					'order_sn' => $order_sn,
					'user_id' => $user_id,
					'price' => $price,
					'rate' => $service_rate,
					'service_price' => $price - $real_price,
					'real_price' => $real_price,
					'type' => 2,
					'real_name' => $real_name,
					'bank_name' => $bank_name,
					'bank_num' => $bank_num,
					'bank_deposit' => $bank_deposit,
					'create_time' => $time
				];
				Db::name('withdrawal')->insert($data);
			}

			$user_data = [
				'all_profit' => $user_info['all_profit'] - $price,
				'real_name' => $real_name,
				'bank_name' => $bank_name,
				'bank_num' => $bank_num,
				'bank_deposit' => $bank_deposit
			];
			Db::name('user')->where(['id' => $user_id])->update($user_data);

			Db::commit();
			apiReturn(1, '申请提现成功');
		} catch (\Exception $e) {
			Db::rollback();
			apiReturn(2, '系统繁忙，请稍后再试~' . $e);
		}
	}

	/**
	 * 订单列表
	 * */
	public function orderList()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$status = $input['status'] ?: 0;
		$page = $input['page'] ?: 1;
		$pagesize = $input['pagesize'] ?: 10;

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		$where['user_id'] = $user_id;
		$where['is_del'] = 0;
		if ($status) $where['status'] = $status;
		$list = Db::name('order')->field('id,order_sn,pay_price,status')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['status_desc'] = doOrderStatus($v['status']);

				$goods_list = Db::name('vice_order')->field('id,img,name,price,count,sku_id')->where(['order_id' => $v['id']])->select();
				if ($goods_list) {
					foreach ($goods_list as &$val) {
						$val['img'] = getPicture($val['img']);
						if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));
					}
					$v['goods_list'] = $goods_list;
				}
			}

			apiReturn(1, '获取数据成功', $list);
		} else {
			apiReturn(2, '暂无更多数据', []);
		}
	}

	/**
	 * 订单详情
	 * */
	public function orderDetail()
	{
		$input = Request()->param();

		$id = $input['id'];

		if (empty($id)) apiReturn(2, '订单ID缺失');

		$info = Db::name('order')->field('id,order_sn,all_price,freight_price,coupon_id,remark,pay_price,status,pay_type,express_id,send_num,get_username,get_mobile,get_province,get_city,get_area,get_address,create_time')->where(['id' => $id])->find();
		if ($info) {
			$info['create_time'] = timeFormat($info['create_time'], 'Y.m.d H:i:s');
			$info['status_desc'] = doOrderStatus($info['status']);

			$coupon_price = 0;
			if ($coupon_id = $info['coupon_id']) $coupon_price = Db::name('user_coupon')->where(['id' => $coupon_id])->value('face_price');
			$info['coupon_price'] = sprintf('%.2f', $coupon_price);

			if ($express_id = $info['express_id']) $info['express_name'] = Db::name('express')->where(['id' => $express_id])->value('name');

			$goods_list = Db::name('vice_order')->field('id,goods_id,img,name,price,count,sku_id,gift_ids')->where(['order_id' => $id])->select();
			if ($goods_list) {
				foreach ($goods_list as &$val) {
					$val['img'] = getPicture($val['img']);
					if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));

					$gift_list = [];
					if ($val['gift_ids']) $gift_list = Db::name('goods_gift')->field('id,gift_img,gift_name,gift_price')->where(['id' => ['IN', $val['gift_ids']], 'is_del' => 0, 'start_date' => ['elt', date('Y-m-d')], 'end_date' => ['egt', date('Y-m-d')]])->select();
					if ($gift_list) {
						foreach ($gift_list as &$value) {
							$value['gift_img'] = getPicture($value['gift_img']);
						}
					}
					$val['gift_list'] = $gift_list;
				}

				$info['goods_list'] = $goods_list;
			}

			apiReturn(1, '获取数据成功', $info);
		} else {
			apiReturn(2, '订单不存在或已删除');
		}
	}

	/**
	 * 信息设置回显数据
	 * */
	public function userInfo()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		$user_info = Db::name('user')->field('id,avatar,username,gender,mobile')->where(['id' => $user_id])->find();
		if ($user_info) {
			$user_info['avatar_path'] = doAvatar($user_info['avatar']);
			$user_info['hide_mobile'] = hideMobile($user_info['mobile']);

			$address_info = Db::name('address')->field('province_id,city_id,area_id')->where(['user_id' => $user_id])->order('is_default desc')->find();
			if ($address_info) {
				$address = getProvinceName($address_info['province_id']) . getCityName($address_info['city_id']) . getAreaName($address_info['area_id']);
				$user_info['address'] = $address;
			} else {
				$user_info['address'] = '';
			}

			apiReturn(1, '获取数据成功', $user_info);
		} else {
			apiReturn(2, '用户信息不存在或已禁用');
		}
	}

	/**
	 * 保存用户信息
	 * */
	public function saveUserInfo()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$avatar = $input['avatar'];
		$username = $input['username'];
		$gender = $input['gender'];
		$mobile = $input['mobile'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
		if (empty($avatar)) apiReturn(2, '请上传头像');
		if (empty($username)) apiReturn(2, '请输入昵称');

		$info = Db::name('user')->where(['id' => $user_id])->find();

		if ($info) {
			$data = [
				'avatar' => $avatar,
				'username' => $username,
				'gender' => $gender,
				'mobile' => $mobile,
				'update_time' => time()
			];

			$res = Db::name('user')->where(['id' => $user_id])->update($data);
			if ($res) {
				apiReturn(1, '保存成功');
			} else {
				apiReturn(2, '保存失败');
			}
		} else {
			apiReturn(2, '用户不存在或已删除');
		}
	}

	/**
	 * 我的券包
	 * */
	public function couponList()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$status = $input['status'] ?: 0;
		$page = $input['page'] ?: 1;
		$pagesize = $input['pagesize'] ?: 10;

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		$where['user_id'] = $user_id;
		$where['is_del'] = 0;
		if ($status) $where['status'] = $status;

		$list = Db::name('user_coupon')->field('id,coupon_name,full_price,face_price,expire_time,status,create_time')->where($where)->order('status asc,expire_time asc')->page($page, $pagesize)->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['expire_time'] = str_replace('-', '.', $v['expire_time']);
				$v['desc'] = '限' . timeFormat($v['create_time'], 'Y.m.d') . '-' . $v['expire_time'] . '期间使用';
			}

			apiReturn(1, '获取数据成功', $list);
		} else {
			apiReturn(2, '暂无更多数据', []);
		}
	}

	/**
	 * 我的收藏
	 * */
	public function collectList()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$page = $input['page'] ?: 1;
		$pagesize = $input['pagesize'] ?: 10;

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		$list = Db::name('collect c')
			->join('xindu_goods g', 'c.to_id = g.id', 'left')
			->field('g.id,g.img,g.name,g.min_price,g.min_vip_price')
			->where(['user_id' => $user_id, 'type' => 1, 'status' => 1])
			->page($page, $pagesize)
			->select();

		if ($list) {
			$user_level = Db::name('user')->where(['id' => $user_id])->value('level');

			foreach ($list as &$v) {
				$price = $user_level > 1 ? $v['min_vip_price'] : $v['min_price'];
				$v['price'] = sprintf('%.2f', $price);
				$v['img'] = getPicture($v['img']);
			}

			apiReturn(1, '获取数据成功', $list);
		} else {
			apiReturn(2, '暂无更多数据', []);
		}
	}

	/**
	 * 我的分享
	 * */
	public function getShareData()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

		//分享二维码
		$qr = Db::name('user')->where(['id' => $user_id])->value('qr');
		if (!$qr) {
			$qr = createUserQr($user_id);
		}
		$qr = getPicture($qr);

		// 顾客总数：形成上下级关系
		$bind_user_count = Db::name('user')->where(['up_user_id' => $user_id])->count();

		// 成功分享：已激活的总数
		$success_user_count = Db::name('user')->where(['up_user_id' => $user_id])->count();

		// 今日新增
		$start_time = strtotime(date('Y-m-d'));
		$end_time = strtotime(date('Y-m-d')) + 24 * 3600 - 1;
		$today_bind_user_count = Db::name('user')->where(['up_user_id' => $user_id, 'create_time' => ['between', [$start_time, $end_time]]])->count();

		$data = [
			'qr' => $qr,
			'bind_user_count' => $bind_user_count,
			'success_user_count' => $success_user_count,
			'today_bind_user_count' => $today_bind_user_count,
		];

		apiReturn(1, '获取数据成功', $data);
	}

	/**
	 * 意见反馈
	 * */
	public function addFeedback()
	{
		$input = Request()->param();

		$user_id = $input['user_id'];
		$content = $input['content'];

		if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
		if (empty($content)) apiReturn(2, '请输入反馈意见');

		checkContent($content);

		$data = [
			'user_id' => $user_id,
			'content' => $content,
			'create_time' => time()
		];

		$res = Db::name('feedback')->insert($data);
		if ($res) {
			apiReturn(1, '反馈成功');
		} else {
			apiReturn(2, '反馈失败');
		}
	}

	/**
	 * 关于我们
	 * */
	public function aboutUs()
	{
		$content = Db::name('about_us')->where(['id' => 1])->value('content');

		$content = doEditorContent($content);

		apiReturn(1, '获取数据成功', $content);
	}

}
